package com.linzm.leetcode.primary.哈希表.两个数组的交集;

import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author zimingl
 * @Date 2022/10/6 23:08
 * @Description: TODO
 */
public class 哈希表350两个数组的交集II {

    public int[] intersect(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length) {
            return intersect(nums2, nums1);
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums1) {
            int count = map.getOrDefault(num, 0) + 1;
            map.put(num, count);
        }
        int[] intersection = new int[nums1.length];
        int index = 0;
        for (int num : nums2) {
            int count = map.getOrDefault(num, 0);
            if (count > 0) {
                intersection[index++] = num;
                count--;
                if (count > 0) {
                    map.put(num, count);
                } else {
                    map.remove(num);
                }
            }
        }
        return Arrays.copyOfRange(intersection, 0, index);
    }

    @Test
    public void test(){
        int[] nums1 = new int[]{4,9,5,9};
        int[] nums2 = new int[]{9,4,9,8,4};

        int[] intersection = intersect(nums1, nums2);

    }

    public int[] intersect2(int[] nums1, int[] nums2) {
        if (nums1.length > nums2.length){
            intersect2(nums2, nums1);
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int num: nums1){
            int count = map.getOrDefault(num, 0) + 1;
            map.put(num, count);
        }
        int[] resultArr = new int[nums1.length];
        int index = 0;
        for (int num : nums2) {
            int count = map.getOrDefault(num, 0);
            if (count > 0){
                count --;
                resultArr[index ++] = num;
            }
            if (count > 0){
                map.put(num, count);
            } else {
                map.remove(num);
            }
        }
        return Arrays.copyOfRange(resultArr, 0, index);
    }

}
